import { BACKEND_ERROR_CODE, createFlatRequest, createRequest } from '@sa/axios';
import { localStg } from '@/utils/storage';
import { createProxyPattern, createServiceConfig } from '~/env.config';
import { fetchRefreshToken } from '@/service/api/auth';
import { getRefreshToken } from '@/store/modules/auth/shared';
import { useAuthStore } from '@/store/modules/auth/index';
import whiteList from './whiteList';

const { baseURL, otherBaseURL } = createServiceConfig(import.meta.env);

const isHttpProxy = import.meta.env.VITE_HTTP_PROXY === 'Y';

export const request = createFlatRequest<App.Service.Response>(
  {
    baseURL: isHttpProxy ? createProxyPattern() : baseURL,
    withCredentials: true,
    headers: {
      apifoxToken: 'XL299LiMEDZ0H5h3A29PxwQXdMJqWyY2'
    }
  },
  {
    async onRequest(config: any) {
      const { headers } = config;
      // set token
      const token = localStg.get('token');
      const Authentication = token ? `${token}` : null;
      console.log(whiteList.includes(config.url), config.url, whiteList);
      Object.assign(headers, {
        Authorization: Authentication && !whiteList.includes(config.url) ? `Bearer ${Authentication}` : ''
      });

      return config;
    },
    isBackendSuccess() {
      return true;
    },
    async onBackendFail(_response) {
      // if (_response.data.status === 302) {
      //   window.$message?.error(_response.data.msg);
      //   resetStore();
      // }
    },
    transformBackendResponse(response) {
      return response.data;
    },
    onError(res) {
      const { refreshToken } = useAuthStore();
      // when the request is fail, you can show error message
      if (res.response?.data.code === 'token_not_valid') {
        fetchRefreshToken(getRefreshToken()).then(res2 => {
          refreshToken(res2.data);
          request(res.config as any);
        });
        return;
      }
      if (res.response?.data.error) {
        window.$message?.error(res.response?.data.error);
        return;
      }
      let message = res.message;

      // show backend error message
      if (res.code === BACKEND_ERROR_CODE) {
        message = res.response?.data?.msg || message;
      }

      window.$message?.error(message);
    }
  }
);

export const demoRequest = createRequest<App.Service.DemoResponse>(
  {
    baseURL: isHttpProxy ? createProxyPattern('demo') : otherBaseURL.demo
  },
  {
    async onRequest(config) {
      const { headers } = config;

      // set token
      const token = localStg.get('token');
      const Authorization = token ? `${token}` : null;
      Object.assign(headers, { Authorization });

      return config;
    },
    isBackendSuccess(response) {
      // when the backend response code is "200", it means the request is success
      // you can change this logic by yourself
      return response.data.status === '200';
    },
    async onBackendFail(_response) {
      // when the backend response code is not "200", it means the request is fail
      // for example: the token is expired, refetch token and retry request
    },
    transformBackendResponse(response) {
      return response.data.result;
    },
    onError(error) {
      // when the request is fail, you can show error message

      let message = error.message;

      // show backend error message
      if (error.code === BACKEND_ERROR_CODE) {
        message = error.response?.data?.message || message;
      }

      window.$message?.error(message);
    }
  }
);
